<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>09_component_lifecycle</title>
</head>
<body>
<div id="example"></div>

<script type="text/javascript" src="../js/react.development.js"></script>
<script type="text/javascript" src="../js/react-dom.development.js"></script>
<script type="text/javascript" src="../js/babel.min.js"></script>
<script type="text/babel">
  /*
  需求: 自定义组件
    1. 让指定的文本做显示/隐藏的动画
    2. 切换时间为2S
    3. 点击按钮从界面中移除组件界面
  */

  /* 
  1. 初始化: 浸染组件标签 ReactDOM.render(<MyComp/>)
    constructor()
    componentWillMount()
    render()
    componentDidMount()
  2. 更新: 更新状态 this.setState()
    componentWillUpdate()
    render()
    componentDidUpdate()
  3. 卸载: 卸载组件  RectDOM.unmountComponentAtNode()
    componentWillUnmount()
   */
  class Life extends React.Component {

    state = {
      opacity: 1
    }

    constructor (props) {
      super(props)
      console.log('constructor()')
    }

    unmountComp = () => {
      // 卸载组件对象(界面会消失)
      ReactDOM.unmountComponentAtNode(document.getElementById('example'))
    }

    componentWillMount () {
      console.log('componentWillMount()')
    }

    /* 
      在第一个render()初始显示组件界面后执行一次
      执行异步任务: 发ajax请求, 启动定时器
     */
    componentDidMount () {
      console.log('componentDidMount()')
      this.intervalId = setInterval(() => {
        console.log('setInterval()...')
        let opacity = this.state.opacity
        opacity -= 0.1
        // 一旦为0, 立即变为1
        if (opacity<=0) {
          opacity = 1
        }

        this.setState({
          opacity
        })
      }, 200)
    }

    componentWillUpdate () {
      console.log('componentWillUpdate()')
    }
    componentDidUpdate () {
      console.log('componentDidUpdate()')
    }

    /* 
    组件对象将要卸载死亡前回调
    做一些收尾的工作: 清除定时器
    */
    componentWillUnmount () {
      console.log('componentWillUnmount()')
      clearInterval(this.intervalId)
    }

    render () {
      console.log('render()')
      const {opacity} = this.state
      return (
        <div>
          <p style={{opacity}}>React学不会, 怎么办?</p>
          <button onClick={this.unmountComp}>不活了</button>
        </div>
      )
    }
  }

  

  ReactDOM.render(<Life/>, document.getElementById('example'))
</script>
</body>
</html>
